<template>
  <view class="container">
    <button @click="startRecognition">开始录音</button>
    <button @click="stopRecognition">停止录音</button>
    <text v-if="recognizedText" class="result">{{ recognizedText }}</text>
  </view>
</template>

<script setup>import { ref } from 'vue';

const APPID = '9d60556f'; // 替换为你的 APPID
const API_KEY = '368bd2098d30b061a84d382de062004f'; // 替换为你的 API_KEY

const socket = ref(null);
const recorderManager = uni.getRecorderManager();
const recognizedText = ref('');

// 构建鉴权 WebSocket 地址
const buildWebSocketUrl = () => {
  const host = 'iat-api.xfyun.cn';
  const path = '/v2/iat';
  const authParam = `?appid=${APPID}&apikey=${API_KEY}`;
  return `wss://${host}${path}${authParam}`;
};

// 判断是否是微信小程序
const isWeChatMiniProgram = () => {
  return typeof wx !== 'undefined' && wx.getFileSystemManager;
};

// 开始语音识别
const startRecognition = () => {
  // 初始化 WebSocket
  const wsUrl = buildWebSocketUrl();
  socket.value = uni.connectSocket({
    url: wsUrl,
    success: () => console.log('WebSocket连接建立成功')
  });

  // WebSocket 打开后发送初始化消息
  socket.value.onOpen(() => {
    const authMessage = {
      common: { app_id: APPID },
      business: { aue: "raw" },
      data: { status: 0 }
    };
    socket.value.send({ data: JSON.stringify(authMessage) });
  });

  // 接收识别结果
  socket.value.onMessage(res => {
    try {
      const result = JSON.parse(res.data);
      if (result.code === 0 && result.data?.result) {
        recognizedText.value = result.data.result;
      }
    } catch (e) {
      console.error("解析失败", e);
    }
  });

  // 开始录音
  recorderManager.start({
    format: 'PCM',
    sampleRate: 16000,
    numberOfChannels: 1,
    encodeBitRate: 48000
  });

  // 【兼容处理】根据平台选择监听方式
  if (typeof recorderManager.onFrameRecorded === 'function') {
    // App 平台支持实时帧录制
    recorderManager.onFrameRecorded(res => {
      const { frameBuffer } = res;
      if (socket.value) {
        socket.value.send({ data: frameBuffer });
      }
    });
  }

  // 录音结束（所有平台都支持）
  recorderManager.onStop(res => {
	  console.log(res);
    const tempFilePath = res.tempFilePath;

    let audioData;

    if (isWeChatMiniProgram()) {
      // 微信小程序专用读取方式
      const fs = wx.getFileSystemManager();
      audioData = fs.readFileSync(tempFilePath);
    } else {
      // 其他平台（App/H5）
      try {
        const readRes = uni.readFileSync({
          filePath: tempFilePath
        });
        audioData = readRes.data;
      } catch (e) {
        console.error('读取录音文件失败', e);
        return;
      }
    }

    if (socket.value && audioData) {
      socket.value.send({ data: audioData }); // 发送整个音频文件内容
    }
  });
};

// 停止录音并结束识别
const stopRecognition = () => {
  recorderManager.stop();

  if (socket.value) {
    // 发送结束标识
    socket.value.send({
      data: JSON.stringify({
        data: { status: 2 }
      })
    });

    socket.value.close(); // 关闭连接
    socket.value = null;
  }
};
</script>

<style scoped>.container {
  padding: 20px;
}
.result {
  margin-top: 20px;
  font-size: 16px;
  color: #333;
}
</style>